﻿using System;
using Newtonsoft.Json.Linq;
using xbmc_json_async.System;
using Newtonsoft.Json;

namespace xbmc_json_async.Application
{
    public class XApplication
    {
        /*
        *  Specification: http://wiki.xbmc.org/index.php?title=JSON-RPC_API/v4#Application
        *  API Methods: Application
        *    5.1.1 Application.GetProperties (Implemented)
        *    5.1.2 Application.Quit (Implemented)
        *    5.1.3 Application.SetMute (Implemented)
        *    5.1.4 Application.SetVolume (Implemented)
        * */
        private XClient Client;
        public Properties.Result propResult;
        /// <summary>
        /// Initializes a new instance of the <see cref="XApplication"/> class.
        /// Eden compatibility only
        /// Throws PlatformNotSupportedException for Dharma
        /// </summary>
        /// <param name="client">The client.</param>
        public XApplication(XClient client)
        {

            Client = client;
        }

        /// <summary>
        /// Gets Properties from XBMC - volume, muted (boolean), name, version
        /// </summary>
        public void GetProperties(XDataReceived userCallback,String[] propertyName)
        {
            var args = new JObject { new JProperty("properties", propertyName) };

            Client.GetData("Application.GetProperties", args, GetPropertiesCallback, userCallback);
        }

        public void GetPropertiesCallback(XRequestState requestState)
        {
            JObject query = JObject.Parse(requestState.ResponseData);
            

            if (query["result"].HasValues)
            {
                propResult = JsonConvert.DeserializeObject<Application.Properties.Result>(query["result"].ToString());
            }
            else { propResult = null; }

            if (requestState.UserCallback != null)
                requestState.UserCallback(propResult);
        }

        /// <summary>
        /// Quits XBMC
        /// </summary>
        public void Quit()
        {
            Client.GetData("Application.Quit", null, null, null);
        }

        /// <summary>
        /// Sets/unsets mute.
        /// </summary>
        public void SetMute()
        {
            Client.GetData("Application.SetMute", null, null, null);
        }

        /// <summary>
        /// Sets the volume.
        /// </summary>
        /// <param name="volume">The volume.</param>
        public void SetVolume(int volume)
        {
            if (volume < 0 | volume > 100) throw new ArgumentException("Value must be between 0 and 100", "volume");

            var args = new JObject { new JProperty("volume", volume) };

            Client.GetData("Application.SetVolume", args, null, null);
        }

    }
}
